package com.gujiangbo.juc;

import java.util.concurrent.*;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/2 20:29
 * @Version: 1.0
 * @Description:
 */
public class CompletableFutureTest {

    public static void main(String[] args) throws Exception {
        // use1();

        // 第一步 ： 计算出结果值
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t come in");
            System.out.println("第一步：开始计算..");
            int result = ThreadLocalRandom.current().nextInt(10);
            //暂停N秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1s 计算出结果:" + result);
            return result;
            // 第二步：根据计算出的结果值 做其他计算
        }).whenComplete((r, e) -> {
            System.out.println("第二步: 根据计算结果计算其他值....");
            Double d = ThreadLocalRandom.current().nextDouble(20) * r;
            //暂停2秒钟线程
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            System.out.println("2s 计算结果:" + d);
        }).exceptionally(e -> {
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + " 开始做其他任务啦....");
        // 主线程不要立即结束，否则CompletableFuture默认的线程池会立即关闭；
        try{TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}


    }

    private static void use1() throws InterruptedException, java.util.concurrent.ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println("task run ...");
        }, executorService);

        CompletableFuture<String> completableFutureWithVal = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return "hello supplyAsync...";
        }, executorService);

        System.out.println(completableFuture.get());
        System.out.println(completableFutureWithVal.get());

        executorService.shutdown();
    }
}